﻿using BySoft.Server.Business;
using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.StockManage
{
    public partial class ScheduleEdit : AuthBasePage
    {
        public DataTable ScheduleDetailDT
        {
            set { Session["ScheduleDetailDT"] = value; }
            get
            {
                if (Session["ScheduleDetailDT"] == null)
                {
                    return CreateDt();
                }
                else
                {
                    return (DataTable)Session["ScheduleDetailDT"];
                }
            }
        }
        public DataTable CreateDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ScheduleDetailID");
            dt.Columns.Add("PlanID");
            dt.Columns.Add("WorkOrderNo");
            dt.Columns.Add("CustomerName");
            dt.Columns.Add("SendCustomerName");
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("Specifications");//规格
            dt.Columns.Add("OutSide");//外径
            dt.Columns.Add("InSide");//内径
            dt.Columns.Add("Unit");//单位
            dt.Columns.Add("OrderNums");//订单数量
            dt.Columns.Add("PlanNum");//计划数量=计划单数量+损耗余量
            dt.Columns.Add("LastNum");//剩余数量=计划单数量－累计排程数量
            dt.Columns.Add("ScheduleNum");//排程数量
            dt.Columns.Add("Remark");
            dt.Columns.Add("ExpectInStockDate");//预计入库日期
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }


        public DataTable ScheduleProcessDT
        {
            set { Session["ScheduleProcessDT"] = value; }
            get
            {
                if (Session["ScheduleProcessDT"] == null)
                {
                    return CreateProcessDt();
                }
                else
                {
                    return (DataTable)Session["ScheduleProcessDT"];
                }
            }
        }
        public DataTable CreateProcessDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ScheduleProcessID");
            dt.Columns.Add("ProcessID");
            dt.Columns.Add("ProcessName");
            dt.Columns.Add("OrderNum");
            dt.Columns.Add("IsCheck");
            dt.Columns.Add("IsOutSource");
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }



        public DataTable ScheduleMachineDT
        {
            set { Session["ScheduleMachineDT"] = value; }
            get
            {
                if (Session["ScheduleMachineDT"] == null)
                {
                    return CreatMachineDt();
                }
                else
                {
                    return (DataTable)Session["ScheduleMachineDT"];
                }
            }
        }
        public DataTable CreatMachineDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ScheduleMachineID");
            dt.Columns.Add("ScheduleProcessID");
            dt.Columns.Add("BillDate");
            dt.Columns.Add("ProcessID");
            dt.Columns.Add("MachineID");
            dt.Columns.Add("ExpectInputTime");
            dt.Columns.Add("SingleStandardProcessTime");
            dt.Columns.Add("AdjustTime");
            dt.Columns.Add("SingleClampTime");
            dt.Columns.Add("ExpectProduceTime");
            return dt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ScheduleProcessDT = null;
                ScheduleDetailDT = null;
                ScheduleMachineDT = null;
                BindProcess();
                InitData();
            }
            txtScheduleID.Attributes.Add("readonly", "true");
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.Page, "iframeAutoFit();");
        }

        private void InitData()
        {
            string ScheduleID = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id"));
            BindHead(ScheduleID);
        }
        /// <summary>
        /// 绑定工序和机台
        /// </summary>
        /// <param name="ScheduleID">排程明细ID</param>
        private void BindBodyProcess(string ScheduleDetailID)
        {
            //工序
            DataTable dt = BsScheduleBusniess.GetScheduleBodyProcessByID(ScheduleDetailID);
            DataTable dtemp = ScheduleProcessDT.Copy();
            //机台
            DataTable dtmachine = ScheduleMachineDT.Copy();
            foreach (DataRow dr in dt.Rows)
            {
                DataRow[] drs = dtemp.Select("ProcessID='" + CommonMethod.GetString(dr["ProcessID"]) + "'");
                if (drs.Length > 0)
                {
                    DataRow d = drs[0];
                    d["ScheduleProcessID"] = CommonMethod.GetString(dr["ScheduleProcessID"]);
                    d["OrderNum"] = CommonMethod.GetString(dr["OrderNum"]);
                    d["IsCheck"] = CommonMethod.GetString(dr["IsCheck"]);
                    d["IsOutSource"] = CommonMethod.GetString(dr["IsOutSource"]);
                    d["IsNew"] = "-1";
                    d["IsDel"] = "-1";
                    string ScheduleProcessID = CommonMethod.GetString(dr["ScheduleProcessID"]);
                    if (!string.IsNullOrEmpty(ScheduleProcessID.ToString()))
                    {
                        DataTable en = BsScheduleMachineBusiness.GetBsSchedulemachineByScheduleProcessID(ScheduleProcessID);
                        if (en != null && en.Rows.Count > 0)
                        {
                            DataRow macDr = en.Rows[0];
                            DataRow[] drr = dtmachine.Select("ScheduleProcessID='" + ScheduleProcessID + "' and ProcessID='" + CommonMethod.GetString(macDr["ProcessID"]) + "'");
                            if (drr.Length <= 0)
                            {
                                DataRow dro = dtmachine.NewRow();
                                dro["ScheduleMachineID"] = CommonMethod.GetString(macDr["ScheduleMachineID"]);
                                dro["ScheduleProcessID"] = CommonMethod.GetString(macDr["ScheduleProcessID"]);
                                dro["BillDate"] = CommonMethod.GetString(macDr["BillDate"]);
                                dro["ProcessID"] = CommonMethod.GetString(macDr["ProcessID"]);
                                dro["MachineID"] = CommonMethod.GetString(macDr["MachineID"]);
                                dro["ExpectInputTime"] = CommonMethod.GetString(macDr["ExpectInputTime"]);
                                dro["SingleStandardProcessTime"] = CommonMethod.GetString(macDr["SingleStandardProcessTime"]);
                                dro["AdjustTime"] = CommonMethod.GetString(macDr["AdjustTime"]);
                                dro["SingleClampTime"] = CommonMethod.GetString(macDr["SingleClampTime"]);
                                dro["ExpectProduceTime"] = string.Format("{0:yyyy-MM-dd}", macDr["ExpectProduceTime"]);
                                dtmachine.Rows.Add(dro);
                            }
                        }
                    }
                }
            }
            ScheduleMachineDT = dtmachine.Copy();//机台
            ScheduleProcessDT = dtemp.Copy();//工序
            grdProcess.DataSource = ScheduleProcessDT;
            grdProcess.DataBind();
        }

        /// <summary>
        /// 绑定产品
        /// </summary>
        /// <param name="ScheduleID">排程ID</param>
        private void BindHead(string ScheduleID)
        {
            //产品明细
            DataTable dt = BsScheduleBusniess.GetScheduleHeadByID(ScheduleID);
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                txtScheduleID.Text = CommonMethod.GetString(dr["ScheduleID"]);
                cpBillDate.Value = string.Format("{0:yyyy-MM-dd}", dr["BillDate"]);
                txtFromDate.Value = string.Format("{0:yyyy-MM-dd}", dr["FromDate"]);
                txtEndDate.Value = string.Format("{0:yyyy-MM-dd}", dr["EndDate"]);

                DataTable dtemp = ScheduleDetailDT.Copy();
                foreach (DataRow drow in dt.Rows)
                {
                    DataRow d =dtemp.NewRow();
                    d["ScheduleDetailID"] = CommonMethod.GetString(drow["ScheduleDetailID"]);
                    d["PlanID"] = CommonMethod.GetString(drow["PlanID"]);
                    d["WorkOrderNo"] = CommonMethod.GetString(drow["WorkOrderNo"]);
                    d["CustomerName"] = CommonMethod.GetString(drow["CustomerName"]);
                    d["SendCustomerName"] = CommonMethod.GetString(drow["SendCustomerName"]);
                    d["ProductID"] = CommonMethod.GetString(drow["ProductID"]);
                    d["ProductName"] = CommonMethod.GetString(drow["ProductName"]);
                    d["Specifications"] = CommonMethod.GetString(drow["Specifications"]);
                    d["OutSide"] = CommonMethod.GetString(drow["OutSide"]);
                    d["InSide"] = CommonMethod.GetString(drow["InSide"]);
                    d["Unit"] = CommonMethod.GetString(drow["Unit"]);
                    d["OrderNums"] = CommonMethod.GetString(drow["OrderNums"]);
                    d["PlanNum"] = CommonMethod.GetString(drow["PlanNums"]);
                    d["LastNum"] = CommonMethod.GetString(drow["LastNum"]);
                    d["ScheduleNum"] = CommonMethod.GetString(drow["ScheduleNum"]);
                    d["Remark"] = CommonMethod.GetString(drow["Remark"]);
                    d["ExpectInStockDate"] = string.Format("{0:yyyy-MM-dd}", drow["ExpectInStockDate"]);
                    d["IsNew"] = "-1";
                    d["IsDel"] = "-1";
                    dtemp.Rows.Add(d);

                    BindBodyProcess(CommonMethod.GetString(drow["ScheduleDetailID"]));
                }
                ScheduleDetailDT = dtemp.Copy();
            }
            BindPro();
        }

        
        private void BindProcess()
        {
            //DataTable dt = SysParameter.GetDSByCondition("ParameterTypeID='Process'").Tables[0];
            DataTable dt = MdProcessBusiness.GetAllData();
            DataTable dtemp = ScheduleProcessDT.Copy();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow drow = dtemp.NewRow();
                    drow["ScheduleProcessID"] = "-1";
                    drow["ProcessID"] = CommonMethod.GetString(dr["ProcessID"]);
                    drow["ProcessName"] = CommonMethod.GetString(dr["ProcessName"]);
                    drow["OrderNum"] = string.Empty;
                    drow["IsCheck"] = string.Empty;
                    drow["IsOutSource"] = string.Empty;
                    drow["IsNew"] = "1";
                    drow["IsDel"] = "-1";
                    dtemp.Rows.Add(drow);
                }
                ScheduleProcessDT = dtemp.Copy();
            }
            grdProcess.DataSource = ScheduleProcessDT;
            grdProcess.DataBind();
        }


        private bool ValidateData()
        {
            AddPro();
            DataView dv = new DataView(ScheduleDetailDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt == null || dt.Rows.Count <= 0)
            {
                UIHelper.AlertMessage(this.Page, "请添加产品！");
                return false;
            }
            AddProcess();
            if (ScheduleMachineDT == null || ScheduleMachineDT.Rows.Count <= 0)
            {
                UIHelper.AlertMessage(this.Page, "请选择机台！");
                return false;
            }
            return true;
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.txtScheduleID.Text.Trim()))
                {
                    BsScheduleEntity entity = new BsScheduleEntity();
                    entity.ScheduleID = GetString(txtScheduleID);
                    entity.BillDate = GetDateTime(cpBillDate);
                    entity.FromDate = GetDateTime(txtFromDate);
                    entity.EndDate = GetDateTime(txtEndDate);
                    entity.CreateDate = DateTime.Now;
                    entity.CreateUserID = CurrentUser.UserID;
                    entity.CreateUserName = CurrentUser.UserName;


                    if (BsScheduleBusniess.SaveOrUpdate(entity, ScheduleDetailDT, ScheduleProcessDT, ScheduleMachineDT, "Update"))
                    {
                        base.LogAction(BaseEnum.ActionType.Modify, entity.ScheduleID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../StockManage/ScheduleList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }
            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        #region Product
        private void BindPro()
        {
            DataView dv = new DataView(ScheduleDetailDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            dt.Columns.Add("OrderNum");
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["OrderNum"] = index;
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.UpdatePanel4, "iframeAutoFit();");
        }
        private void AddPro()
        {
            ScheduleDetailDT = GetAddPro(ScheduleDetailDT).Copy();
        }
        private DataTable GetAddPro(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblScheduleDetailID = gvr.FindControl("lblScheduleDetailID") as Label;
                    Label lblPlanID = gvr.FindControl("lblPlanID") as Label;
                    Label lblWorkOrderNo = gvr.FindControl("lblWorkOrderNo") as Label;
                    Label lblCustomerName = gvr.FindControl("lblCustomerName") as Label;
                    Label lblSendCustomerName = gvr.FindControl("lblSendCustomerName") as Label;
                    Label lblProductID = gvr.FindControl("lblProductID") as Label;
                    Label lblProductName = gvr.FindControl("lblProductName") as Label;
                    Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                    Label lblOutSide = gvr.FindControl("lblOutSide") as Label;
                    Label lblInSide = gvr.FindControl("lblInSide") as Label;
                    Label lblUnit = gvr.FindControl("lblUnit") as Label;
                    Label lblOrderNums = gvr.FindControl("lblOrderNums") as Label;
                    Label lblPlanNum = gvr.FindControl("lblPlanNum") as Label;
                    Label lblLastNum = gvr.FindControl("lblLastNum") as Label;
                    TextBox txtScheduleNum = gvr.FindControl("txtScheduleNum") as TextBox;
                    TextBox txtRemark = gvr.FindControl("txtRemark") as TextBox;
                    TextBox txtExpectInStockDate = gvr.FindControl("txtExpectInStockDate") as TextBox;


                    string WorkOrderNo = CommonMethod.GetString(lblWorkOrderNo.Text);


                    DataRow[] drs = dtTemp.Select("WorkOrderNo='" + WorkOrderNo + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["ScheduleDetailID"] = GetGridViewString(lblScheduleDetailID);
                        drs[0]["PlanID"] = GetGridViewString(lblPlanID);
                        drs[0]["WorkOrderNo"] = GetGridViewString(lblWorkOrderNo);
                        drs[0]["CustomerName"] = GetGridViewString(lblCustomerName);
                        drs[0]["SendCustomerName"] = GetGridViewString(lblSendCustomerName);
                        drs[0]["ProductID"] = GetGridViewString(lblProductID);
                        drs[0]["ProductName"] = GetGridViewString(lblProductName);
                        drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                        drs[0]["OutSide"] = GetGridViewString(lblOutSide);
                        drs[0]["InSide"] = GetGridViewString(lblInSide);
                        drs[0]["Unit"] = GetGridViewString(lblUnit);
                        drs[0]["OrderNums"] = GetGridViewString(lblOrderNums);
                        drs[0]["PlanNum"] = GetGridViewString(lblPlanNum);
                        drs[0]["LastNum"] = GetGridViewString(lblLastNum);
                        drs[0]["ScheduleNum"] = GetGridViewString(txtScheduleNum);
                        drs[0]["Remark"] = GetGridViewString(txtRemark);
                        drs[0]["ExpectInStockDate"] = GetGridViewString(txtExpectInStockDate);
                    }
                }
            }
            return dtTemp;
        }
        #endregion

        #region Process
        private void AddProcess()
        {
            ScheduleProcessDT = GetAddProcess(ScheduleProcessDT).Copy();
        }
        private DataTable GetAddProcess(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdProcess.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblScheduleProcessID = gvr.FindControl("lblScheduleProcessID") as Label;
                    Label lblProcessID = gvr.FindControl("lblProcessID") as Label;
                    Label lblProcessName = gvr.FindControl("lblProcessName") as Label;
                    TextBox txtOrderNum = gvr.FindControl("txtOrderNum") as TextBox;
                    CheckBox chkIsCheck = gvr.FindControl("chkIsCheck") as CheckBox;
                    CheckBox chkIsOutSource = gvr.FindControl("chkIsOutSource") as CheckBox;


                    string ProcessID = CommonMethod.GetString(lblProcessID.Text);


                    DataRow[] drs = dtTemp.Select("ProcessID='" + ProcessID + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["ScheduleProcessID"] = GetGridViewString(lblScheduleProcessID);
                        drs[0]["ProcessID"] = GetGridViewString(lblProcessID);
                        drs[0]["ProcessName"] = GetGridViewString(lblProcessName);
                        drs[0]["OrderNum"] = GetGridViewString(txtOrderNum);
                        drs[0]["IsCheck"] = chkIsCheck.Checked ? "1" : "0";
                        drs[0]["IsOutSource"] = chkIsOutSource.Checked ? "1" : "0";
                        string OrderNum = GetString(txtOrderNum);
                        if (string.IsNullOrEmpty(OrderNum) || OrderNum == "0")
                        {
                            drs[0]["IsDel"] = "1";
                        }
                    }
                }
            }
            return dtTemp;
        }
        #endregion

        protected void grdProcess_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkIsCheck = (CheckBox)e.Row.FindControl("chkIsCheck");
                CheckBox chkIsOutSource = (CheckBox)e.Row.FindControl("chkIsOutSource");
                string IsCheck = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["IsCheck"].ToString().Trim();
                string IsOutSource = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["IsOutSource"].ToString().Trim();
                if (!string.IsNullOrEmpty(IsCheck) && IsCheck.Equals("1"))
                {
                    chkIsCheck.Checked = true;
                }
                else
                {
                    chkIsCheck.Checked = false;
                }
                if (!string.IsNullOrEmpty(IsOutSource) && IsOutSource.Equals("1"))
                {
                    chkIsOutSource.Checked = true;
                }
                else
                {
                    chkIsOutSource.Checked = false;
                }
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
            }
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "del":
                    AddPro();
                    DataTable dt = ScheduleDetailDT.Copy();
                    DataRow[] dr = dt.Select("WorkOrderNo='" + strCode.Trim() + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    ScheduleDetailDT = dt.Copy();
                    BindPro();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void btnHidden_Click(object sender, EventArgs e)
        {
            AddPro();
            BindPro();
        }
    }
}